import 'dart:convert';

import 'dart:io';

class ErrorQrcodeData implements Exception {}
class GetLocalAddrFailed implements Exception {}

/// 用户扫描二维码，发现服务器地址
/// 二维码样式 前导码 esync
/// 长度字节 1，代表共有多少个 ipv4 地址
/// 剩下为 n * 4 长度
/// ZXN5bmMDwKg4AcCoCrzAqAJs
List<InternetAddress> _parseServerAddr(String qr) {
  var data = base64Decode(qr);
  print(data[0] == 'e'.codeUnitAt(0));
  print(String.fromCharCodes(data, 0, 5));
  if(String.fromCharCodes(data, 0, 5) != "esync") {
    print('qr magic not match');
    throw ErrorQrcodeData();
  }

  var ipLength = data[5];
  if(data.length != 5 + 1 + ipLength * 4) {
    print('ip length not match');
    throw ErrorQrcodeData();
  }

  var ipArray = <InternetAddress>[];
  for(var i=0; i!=ipLength; ++i) {
    var start = 6 + i * 4;

    var curAddrs = <String>[];
    for(var j=0; j!=4; ++j) {
      curAddrs.add(data[start + j].toString());
    }

    var addr = InternetAddress(curAddrs.join("."));
    print(addr.toString());
    ipArray.add(addr);
  }

  return ipArray;
}

List<InternetAddress> parseServerAddr(String qr) {
  try {
    return _parseServerAddr(qr);
  } on FormatException {
    print('qr parse failed');
    throw ErrorQrcodeData();
  }
}

/// 通过本地IP地址，比较并获取服务器地址
///
String diffIpAddrs(List<InternetAddress> ipArray, InternetAddress localAddr) {
  for(var curIp in ipArray) {
    // 如果前三个值相同，最后一个只 不同，则认定为服务器地址
    var ipRaw = curIp.rawAddress;
    var localRaw = localAddr.rawAddress;
    if(ipRaw[0] == localRaw[0] &&
        ipRaw[1] == localRaw[1] &&
        ipRaw[2] == localRaw[2]
    ) {
      return curIp.address;
    }
  }

  return "";
}

void main() {
  //
  parseServerAddr("ZXN5bmMDwKg4AcCoCrzAqAJs");
}
